package cn.zou.db;



import com.alibaba.druid.pool.DruidDataSource;
import com.mysql.jdbc.Driver;
import org.apache.log4j.Logger;
import org.junit.Test;


import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created by zou on 2017/7/10.
 * 数据库连接管理对象
 */
public class DBManager {
    //获取阿里巴巴的连接池
   private  DruidDataSource dataSource  = new DruidDataSource();
   private static final Logger logger = Logger.getLogger(DBManager.class);
    //初始化时建立物理连接的个数。初始化发生在显示调用init方法，或者第一次getConnection时
   private int INITIALSIZE=20;
   private int MAXACTIVE=30;// 最大连接池数量
   private int MINIDLE=0;//最小连接词数量
   private int MAXWAIT=6000;//最大连接数量
   private Boolean  POOLPREPAREDSTATEMENTS=false;//是否缓存preparedStatement，也就是PSCache。PSCache对支持游标的数据库性能提升巨大，比如说oracle。在mysql下建议关闭。
    @Test
    public Connection getCon(){
        try {
            return getdataSource().getConnection();
        } catch (SQLException e) {
            logger.error("数据库连接失败");
        }
        return null;
    }

    public DruidDataSource getdataSource(){
       Properties p=getPeperties();
       String driver=p.getProperty("jdbc.driverClassName");
       String url=p.getProperty("jdbc.url");
       String username=p.getProperty("jdbc.username");
       String password=p.getProperty("jdbc.password");
       dataSource.setUrl(url);
       dataSource.setDriverClassName(driver);
       dataSource.setUsername(username);
       dataSource.setPassword(password);
       dataSource.setInitialSize(INITIALSIZE);
       dataSource.setMaxActive(MAXACTIVE);
       dataSource.setMinIdle(MINIDLE);
       dataSource.setMaxWait(MAXWAIT);
       dataSource.setPoolPreparedStatements(POOLPREPAREDSTATEMENTS);
       return dataSource;
   }

    public void setInitialSize(int initialSize) {
        INITIALSIZE = initialSize;
    }

    public void setMaxActive(int maxActive) {
        MAXACTIVE = maxActive;
    }

    public void setMinIdle(int minIdle) {
        MINIDLE = minIdle;
    }

    public void setMaxWait(int maxWait) {
        MAXWAIT = maxWait;
    }

    public void setPoolPreparedStatements(Boolean poolPreparedStatements) {
        POOLPREPAREDSTATEMENTS = poolPreparedStatements;
    }

    public String getPath(){
      String path= DBManager.class.getResource("").toString();
      int i = path.indexOf("/class");
      String substring = path.substring(0, i);
      String s = substring.replaceAll("file:/", "");
     return s+"/src/jdbc.properties";

   }
   public Properties getPeperties(){
      try {
         InputStream is=new BufferedInputStream(new FileInputStream(new File(getPath())));
         Properties p=new Properties();
         p.load(is);
         return p;
      } catch (Exception e) {
         logger.error(e);
      }
      return null;
   }
}
